package demo3IOliu;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @description:字节流的操作
 * @author:Mr.Cat
 * @create:2021-11-07 21:55
 **/
public class FileInputOutputStreamTest {
    @Test
    public void test1() {
        //实例化File
        FileInputStream fis = null;
        try {
            File file = new File("Hello.txt");
            //造流
            fis = new FileInputStream(file);
            //读数据
            byte[] buffer = new byte[5];
            int len;//记录每次读取的字节的个数
            while ((len = fis.read(buffer)) != -1) {
                String str = new String(buffer, 0, len);
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    //实现对图片的复制操作
    @Test
    public void test2() {
        //实例化
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            File srcfile = new File("mm.png");
            File destfile = new File("MM.pnf");

            //造流
            fis = new FileInputStream(srcfile);
            fos = new FileOutputStream(destfile);

            //读取输入过程
            byte[] buffer = new byte[5];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos!=null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

